//
//  MyPurchaseViewController.m
//  YYPHSpeedJump
//
//  Created by speedjump on 16/1/28.
//  Copyright © 2016年 sujiang. All rights reserved.
//

#import "MyPurchaseViewController.h"
#import "MyPurchaseCollectionViewCell.h"
#import "ShaiXuanTableViewCell.h"
#import "AddPuechaseViewController.h"
#import "PurchaseDetailViewController.h"
@interface MyPurchaseViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate>
{
    NSInteger page;
    NSInteger status;
}
@property (nonatomic ,strong)NSMutableArray *shaixuanArray;
@end

@implementation MyPurchaseViewController

- (NSMutableArray *)myxyArr
{
    if (!_myxyArr) {
        _myxyArr = [NSMutableArray array];
    }
    return _myxyArr;
}
- (NSMutableArray *)shaixuanArray
{
    if (!_shaixuanArray) {
        _shaixuanArray = [NSMutableArray arrayWithObjects:@"全部",@"正在进行中",@"即将上线",@"完成", nil];
    }
    return _shaixuanArray;
}
- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
     [self.myxyArr removeAllObjects];
    page=1;
    status = 0;
   
    [self requestData];
      // [self.collectionView reloadData];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"我的心愿夹";
    //筛选功能
    //self.rightBtn= [[UIBarButtonItem alloc]initWithTitle:@"筛选" style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnAction:)];
    
    //self.navigationItem.rightBarButtonItem = self.rightBtn;
    //[self requestData];
    
    [self addSubViews];
}
- (void)requestData
{
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"logined"]) {
        [Tools showAlert:@"您还未登录,请到个人登录!"];
        return;
    }
    NSString *myXYUrlStr = [NSString stringWithFormat:@"%@%@",kBaseUrl,kMYXYUrl];
    NSDictionary *dic = @{@"u":[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"], @"page":[NSNumber numberWithInteger:page],@"status":[NSNumber numberWithInteger:status]};
    [NetworkHandle getUpDataWithUrl:myXYUrlStr class:NSClassFromString(@"PurchaseModel") dictionary:dic firstKey:@"data" secondKey:@"list" success:^(NSArray *array) {
        
        if (page == 1) {
            [self.myxyArr removeAllObjects];
        }
        [self.myxyArr addObjectsFromArray:array];
        if(self.myxyArr.count == 0)
        {
            self.label = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, kScreenWidth,36)];
            self.label.text = @"你还没有许愿，请点击添加按钮前往许愿";
            self.label.font = [UIFont systemFontOfSize:12];
            self.label.textAlignment = NSTextAlignmentCenter;
            [self.collectionView addSubview:self.label];
        } else {
            [self.label removeFromSuperview];
            if (self.myxyArr.count >= 10 && self.collectionView.footer == nil) {
                self.collectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
            }
        }
        [self.collectionView.header  endRefreshing];
        [self.collectionView.footer endRefreshing];
        [self.collectionView reloadData];    }];
}
- (void)addSubViews
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing =9*kWidthScale;
    layout.itemSize = CGSizeMake((kScreenWidth-20*kWidthScale)/3, 145);
    NSLog(@"%f",[UIScreen mainScreen].bounds.size.width);
    layout.sectionInset = UIEdgeInsetsMake(5, 5*kWidthScale,5,5*kWidthScale);
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-10) collectionViewLayout:layout];
    self.collectionView.backgroundColor =[UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource =self;
    
    [self.view addSubview:self.collectionView];
    [self.collectionView registerNib:[UINib nibWithNibName:@"MyPurchaseCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"myPurchaseCell"];
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.frame = CGRectMake(0, kScreenHeight-44-64,kScreenWidth, 44);
    [addBtn setBackgroundColor:kColors(218, 166, 46, 1)];
    [addBtn setTitle:@"添加心愿" forState:UIControlStateNormal];
    addBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    //addBtn.layer.cornerRadius = 0;
    [addBtn addTarget:self action:@selector(addBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addBtn];

}

#pragma mark --------------- button 点击事件-----------------
- (void)rightBtnAction:(UIBarButtonItem *)btn
{
    self.rightBtn.enabled = NO;
    
    self.shaixuanView = [[UIView alloc]initWithFrame:CGRectMake(246*kWidthScale, 0, 117*kWidthScale, 185)];
    UIImageView *imageV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 117*kWidthScale, 185)];
    imageV.image = [UIImage imageNamed:@"shaixuan"];
    [self.shaixuanView addSubview:imageV];
//    self.shaixuanView.backgroundColor = [UIColor whiteColor];
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 10,self.shaixuanView.width, 175)];
    tableView.delegate =self;
    tableView.dataSource = self;
    tableView.backgroundColor = [UIColor clearColor];
    tableView.scrollEnabled = NO;
    tableView.separatorStyle =  UITableViewCellSeparatorStyleNone;
    [self.shaixuanView addSubview:tableView];
    [self.view addSubview:self.shaixuanView];
}
- (void)footerRefresh

{
    page++;
    [self requestData];
}

//添加心愿
- (void)addBtnAction:(UIButton *)btn

{
    AddPuechaseViewController *addVC = [[AddPuechaseViewController alloc]init];
    [self.navigationController pushViewController:addVC animated:YES];
}
#pragma mark --------------- tabelViewdelegate --------------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.shaixuanArray.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ShaiXuanTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"shaixuanCell"];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"ShaiXuanTableViewCell" owner:nil options:nil]lastObject];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
  
    cell.titleLabel.text = self.shaixuanArray[indexPath.row];
    return cell;
}
 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 43;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.myxyArr removeAllObjects];
    if (indexPath.row == 0) {
        page =1;
        status =0;
        [self.myxyArr removeAllObjects];
        [self requestData];
        [self.collectionView reloadData];
    }
    if (indexPath.row == 1) {
         page =1;
        status =1;
         [self.myxyArr removeAllObjects];
        [self requestData];
        [self.collectionView reloadData];
    }
    if (indexPath.row == 2) {
         page =1;
        status =3;
         [self.myxyArr removeAllObjects];
        [self requestData];
        [self.collectionView reloadData];
    }
    if (indexPath.row == 3) {
         page =1;
        status =4;
         [self.myxyArr removeAllObjects];
        [self requestData];
        [self.collectionView reloadData];
    }
    self.rightBtn.enabled = YES;
    [self.shaixuanView removeFromSuperview];
}
#pragma mark-------------collectionViewDelegate------------------
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.myxyArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MyPurchaseCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myPurchaseCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    cell.model = self.myxyArr[indexPath.row];
    UILongPressGestureRecognizer *longPressGR = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handlelongPress:)];
    [cell addGestureRecognizer:longPressGR];
    longPressGR.minimumPressDuration = 1.0;
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    PurchaseDetailViewController *purchaseDetailVC =[[PurchaseDetailViewController alloc]init];
    [self.navigationController pushViewController:purchaseDetailVC animated:YES];
    purchaseDetailVC.purchaseModel =self.myxyArr[indexPath.row];
}
- (void)handlelongPress:(UILongPressGestureRecognizer*)recognizer
{
    CGPoint point = [recognizer locationInView:self.collectionView];
    self.indexPath = [self.collectionView indexPathForItemAtPoint:point];
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"是否删除本条心愿" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {//取消
       
    }else if (buttonIndex == 1){//确定
       
         MyPurchaseCollectionViewCell *cell1 = (MyPurchaseCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:self.indexPath];
                NSString *deleteUrlStr = [NSString stringWithFormat:@"%@/user.do?cmd=delete_my_wish",kBaseUrl];
        NSDictionary *dic = @{@"u":[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"], @"wish_id":cell1.model.wish_id};
        [NetworkHandle getInfoWithUrl:deleteUrlStr dictionary:dic success:^(NSDictionary *dictionary) {
            // NSLog(@"%@", dictionary);
            if([dictionary[@"code"] isEqualToString:@"200"]){
                [self.myxyArr removeObjectAtIndex:self.indexPath.row];
                [self.collectionView deleteItemsAtIndexPaths:@[self.indexPath]];
                if (self.myxyArr.count ==0) {
                    
                    self.label = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, kScreenWidth, 36)];
                    self.label.text = @"你还没有许愿，请点击添加按钮前往许愿";
                    self.label.font = [UIFont systemFontOfSize:12];
                    self.label.textAlignment = NSTextAlignmentCenter;
                    [self.collectionView addSubview:self.label];

                }

            }
            else
            {
                [Tools showAlert:@"删除失败"];
            }
        }];

    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
